<?php
// Date:   01/03/09
// File:   snarf.lib.php
// Desc:   This file is the lib for Snarf.

class snarfer {

	public function GetGoogleResults( $query,$page=1,$perpage=10, $dc="www.google.com",$filter=true){
	 if($page) $page--;
    $url=sprintf("http://%s/ie?q=%s&num=%d&start=%d&hl=en&ie=UTF-8&filter=%d&c2coff=1&safe=off", $dc,urlencode($query),$perpage,$page*$perpage,$filter);
	 //DEBUG echo $url;
    //$html = file_get_contents($url);
	 $ch = curl_init($url);
	 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	 $html = curl_exec($ch);
	 curl_close($ch);
	 //echo $html;
    if(!preg_match_all( "/<nobr>(.+?)<\/nobr>/is", $html, $matches))
        return false;
    $matches=$matches[1];
    $results=array();
    for($i=0;$i<count($matches);$i++){
        $match=trim($matches[$i]);
        if(!preg_match_all( "/(.+?)\.\s<a title=[\"](.+?)[\"] href=(.+?)>(.+?)<\/a>/i",
            $match, $parts)) continue;
        $parts[4][0]=strip_tags($parts[4][0]);
        array_splice($parts,0,1);
        $LinkTitle    =trim($parts[3][0],"\r\n\t \"");
        $LinkDesc    =trim($parts[1][0],"\r\n\t \"");
        $Rank        =trim($parts[0][0]);
        $LinkUrl    =trim($parts[2][0],"\r\n\t \"");
        if(!strstr($LinkUrl,"://"))
            continue;
        if(!preg_match("/^([^:]+):\/\/([^\/]+)[\/]?(.*)$/",$LinkUrl,$Dom)){
            continue;
        }
        $Http=$Dom[1];
        $Rel="/".$Dom[3];
        $Dom=$Dom[2];
        $serp=array(
            "Rank"            => $Rank,
            "Url"            => $LinkUrl,
            "Title"            => trim(html_entity_decode(strip_tags($LinkTitle))),
            "Host"            => $Dom,
            "Protocol"        => $Http,
            "Path"            => $Rel,
            "Summary"        => trim(html_entity_decode(strip_tags($LinkDesc))),
        );
        array_push($results,$serp);
    }
    return $results;


	}

	public function GetGoogleLinks($query,$page=1,$pageper=10,$dc="www.google.com",$filter=TRUE) {
		$res = $this->GetGoogleResults($query,$page,$pageper,$dc,$filter);
		$links=array();
		for($i=0;$i<count($res);$i++) {
			$link=$res[$i]['Url'];
			array_push($links,$link);
		}
		return $links;	
	}
}
/*
$debug = new snarfer;
$var = $debug->GetGoogleResults('"Powered by ArticleMS"',1,100);
echo var_dump($var);
*/
?>
